package com.dragons.dragonsvf.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dragons.dragonsvf.dao.UserInfoMapper;
import com.dragons.dragonsvf.entities.*;
import com.dragons.dragonsvf.utils.netUtils;
import com.dragons.dragonsvf.utils.secret.AesEncryptUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

@RestController
public class LoginCtrl {

    private static final Logger logger = LoggerFactory.getLogger(LoginCtrl.class);

    @Autowired
    private UserInfoMapper userInfoMapper;


    @RequestMapping("/test")
    public String test() {
        return "测试测试";
    }


    // 获取用户信息
    @RequestMapping("/getuserInfo")
    public ResponseDTO getuserInfo(@RequestBody UserDTO user) {
        QueryWrapper<UserInfo> qu = new QueryWrapper<>();
        qu.eq("username", user.getuName())
            .eq("tel_num", user.getuCellphone()).select("*");
        UserInfo userInfo = userInfoMapper.selectOne(qu);
        ResponseDTO res = new ResponseDTO();
        if (userInfo != null) {
            res.setCode(200);
            res.setMsg("登录成功");
            res.setData(userInfo);
        }
        return res;
    }

    // 获取用户信息
    @RequestMapping("/getUserInfoByIdOrNameOrTel")
    public ResponseDTO getUserInfoByIdOrNameOrTel(@RequestBody UserDTO user) {

        UserInfo userInfo = null;
        QueryWrapper<UserInfo> qu = new QueryWrapper<>();
        if (!"".equals(user.getUsrId() == null ? "": user.getUsrId().trim())) {
            qu.eq("id", user.getUsrId().trim());
            userInfo = userInfoMapper.selectOne(qu);
        }
        if (!"".equals(user.getuName() == null ? "": user.getuName().trim())) {
            qu.eq("username", user.getuName().trim());
            userInfo = userInfoMapper.selectOne(qu);
        }
        if (!"".equals(user.getuCellphone() == null ? "": user.getuCellphone().trim())) {
            qu.eq("tel_num", user.getuCellphone().trim());
            userInfo = userInfoMapper.selectOne(qu);
        }

        ResponseDTO res = new ResponseDTO();
        if (userInfo != null){
            UserDTO userDTO = new UserDTO();
            userDTO.setUsrId(userInfo.getId());
            userDTO.setuName(userInfo.getUsername());
            userDTO.setuCellphone(userInfo.getTel_num());
            res.setCode(200);
            res.setData(userDTO);
            res.setMsg("用户信息查询成功");
        } else {
            res.setCode(200);
            res.setMsg("用户信息查询失败");
        }
        return res;
    }

    /** 普通用户 登录 */
    @RequestMapping("/login")
    public ResponseDTO login(@RequestBody UserDTO user) {

        //String token = JwtUtil.createToken(dbUser);
        String encrypt = "";
        if(!"".equals(user.getuPwdword())) {
            try {
                encrypt = AesEncryptUtil.encrypt(user.getuPwdword());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        QueryWrapper<UserInfo> u = new QueryWrapper<>();
        u.eq("username", user.getuName())
            .select("*");
        List<UserInfo> checkPwd = userInfoMapper.selectList(u);

        QueryWrapper<UserInfo> u1 = new QueryWrapper<>();
        u1.eq("username", user.getuName())
            .eq("encrypt_pwd", encrypt)
            .select("*");
        List<UserInfo> userInfos = userInfoMapper.selectList(u1);
        ResponseDTO res = new ResponseDTO();
        if (checkPwd.size() > 0) { // 验证用户是否存在
            if(userInfos.size() > 0) { // 验证密码
                res.setCode(200);
                res.setMsg("登录成功");
                UserInfo userInfo = userInfos.get(0);
                UserInfoDTO userInfoDTO = new UserInfoDTO();
                // 复制属性（注意参数顺序：源对象在前，目标对象在后）
                BeanUtils.copyProperties(userInfo, userInfoDTO);
                String avatarBase64 = netUtils.convertToBase64(userInfo.getAvatar_url());
                userInfoDTO.setAvatarBase64(avatarBase64);
                res.setData(userInfoDTO);
            } else {
                res.setCode(200);
                res.setMsg("密码错误");
            }
        } else {
            res.setCode(200);
            res.setMsg("用户不存在");
        }
        return res;
    }





























    /** ====================== 后台用户管理接口 ============================ */

    @RequestMapping("/getBakUserList") // 后台查询商品列表
    public ResponseDTO getBakUserList(@RequestBody UserBakDTO params){
        ResponseDTO res = new ResponseDTO();

        QueryWrapper<UserInfo> q = new QueryWrapper<>();
        if (!"".equals(params.getId().trim())) {
            q.eq("id", params.getId()); // 用户ID
        }
        if (!"".equals(params.getUname().trim())) {
            q.like("username", params.getUname()); // 用户名
        }
        if (!"".equals(params.getAcrossNum().trim())) {
            q.eq("across_num", params.getAcrossNum()); // 密码
        }
        if (!"".equals(params.getEncryptPwd().trim())) {
            q.eq("encrypt_pwd",params.getEncryptPwd()); // 加密后的密码
        }
        if (!"".equals(params.getEncryptionAlgorithm().trim())) {
            q.eq("encryption_algorithm",params.getEncryptionAlgorithm()); // 加密算法
        }
        if (!"".equals(params.getEmail().trim())) {
            q.like("email",params.getEmail()); // 电子邮件
        }
        if (!"".equals(params.getTelNum().trim())) {
            q.like("tel_num",params.getTelNum()); // 电话号码
        }
        if (!"".equals(params.getWechatAbt().trim())) {
            q.like("wechat_abt",params.getWechatAbt()); // 微信相关信息
        }
        if (!"".equals(params.getAvatarUrl().trim())) {
            q.like("avatar_url",params.getAvatarUrl()); // 头像minio链接
        }
        if (!"".equals(params.getRoleNum().trim())) {
            q.like("role_num",params.getRoleNum()); // 角色编号
        }
        if (params.getFreezeOrnnt()!=null) {
            q.like("freeze_ornnt",params.getFreezeOrnnt()); // 是否冻结 0 不冻结 1 冻结
        }
        if (params.getAccountMoney()!=null && params.getAccountMoney() > 0) {
            q.eq("account_money",params.getAccountMoney()); // 账户金额
        }
        if (params.getbAccount()!=null && params.getbAccount() > 0) {
            q.eq("b_account",params.getbAccount()); // 账户金额
        }
        q.orderByDesc("update_tm");
        Page<UserInfo> page = new Page<>(params.getCurrentPage(), params.getPageSize());
        Page<UserInfo> result = userInfoMapper.selectPage(page, q);
        List<UserInfo> records = result.getRecords();

        List<UserBakDTO> users = new ArrayList<>();
        if (records.size() > 0) {
            for (UserInfo user : records) {
                UserBakDTO u = new UserBakDTO();
                u.setId(user.getId());
                u.setUname(user.getUsername());
                u.setAcrossNum(user.getAcross_num());
                u.setEncryptPwd(user.getEncrypt_pwd());
                u.setEncryptionAlgorithm(user.getEncryption_algorithm());
                u.setEmail(user.getEmail());
                u.setTelNum(user.getTel_num());
                u.setWechatAbt(user.getWechat_abt());
                u.setAvatarUrl(user.getAvatar_url());
                u.setRoleNum(user.getRole_num());
                u.setFreezeOrnnt(user.getFreeze_ornnt());
                u.setAccountMoney(user.getAccount_money());
                u.setbAccount(user.getB_account());
                u.setCreateTm(user.getCreate_tm());
                u.setUpdateTm(user.getUpdate_tm());
                users.add(u);
            }
        }

        res.setCode(200);
        res.setData(users);
        res.setMsg("查询成功");
        return res;
    }

    @RequestMapping("/getBakUserListCount") // 查询订单列表
    public ResponseDTO getBakUserListCount(@RequestBody UserBakDTO params){

        ResponseDTO res = new ResponseDTO();

        QueryWrapper<UserInfo> q = new QueryWrapper<>();
        if (!"".equals(params.getId().trim())) {
            q.eq("id", params.getId()); // 用户ID
        }
        if (!"".equals(params.getUname().trim())) {
            q.like("username", params.getUname()); // 用户名
        }
        if (!"".equals(params.getAcrossNum().trim())) {
            q.eq("across_num", params.getAcrossNum()); // 密码
        }
        if (!"".equals(params.getEncryptPwd().trim())) {
            q.eq("encrypt_pwd",params.getEncryptPwd()); // 加密后的密码
        }
        if (!"".equals(params.getEncryptionAlgorithm().trim())) {
            q.eq("encryption_algorithm",params.getEncryptionAlgorithm()); // 加密算法
        }
        if (!"".equals(params.getEmail().trim())) {
            q.like("email",params.getEmail()); // 电子邮件
        }
        if (!"".equals(params.getTelNum().trim())) {
            q.like("tel_num",params.getTelNum()); // 电话号码
        }
        if (!"".equals(params.getWechatAbt().trim())) {
            q.like("wechat_abt",params.getWechatAbt()); // 微信相关信息
        }
        if (!"".equals(params.getAvatarUrl().trim())) {
            q.like("avatar_url",params.getAvatarUrl()); // 头像minio链接
        }
        if (!"".equals(params.getRoleNum().trim())) {
            q.like("role_num",params.getRoleNum()); // 角色编号
        }
        if (params.getFreezeOrnnt()!=null) {
            q.like("freeze_ornnt",params.getFreezeOrnnt()); // 是否冻结 0 不冻结 1 冻结
        }
        if (params.getAccountMoney()!=null && params.getAccountMoney() > 0) {
            q.eq("account_money",params.getAccountMoney()); // 账户金额
        }
        if (params.getbAccount()!=null && params.getbAccount() > 0) {
            q.eq("b_account",params.getbAccount()); // 账户金额
        }

        Long aLong = userInfoMapper.selectCount(q);

        res.setCode(200);
        res.setData(aLong);
        res.setMsg("查询用户总数成功");
        return res;
    }

    @RequestMapping("/updateBakUserType") // 更新订单状态
    public ResponseDTO updateBakUserType(@RequestBody UserBakDTO params) {

        UpdateWrapper<UserInfo> updw = new UpdateWrapper<>();
        updw.eq("id", params.getId());
        updw.set("freeze_ornnt", params.getFreezeOrnnt());
        updw.set("update_tm", new Timestamp(System.currentTimeMillis()));
        // 执行更新操作  参数1为null表示不依赖实体对象
        int affectedRows = userInfoMapper.update(null, updw);
        // 构造响应结果
        ResponseDTO res = new ResponseDTO();
        res.setCode(200);
        if (affectedRows > 0) {
            res.setMsg("用户状态更新成功");
        } else {
            res.setMsg("用户状态更新失败");
        }
        return res;
    }

    @RequestMapping("/userUpdateBak") // 修用户
    public ResponseDTO userUpdateBak(@RequestBody UserBakDTO user) throws Exception {

        UserInfo u = new UserInfo();
        u.setId(user.getId());
        u.setUsername(user.getUname());
        u.setAcross_num(user.getAcrossNum());
        u.setEncrypt_pwd(AesEncryptUtil.encrypt(user.getAcrossNum()));
        u.setEncryption_algorithm(user.getEncryptionAlgorithm());
        u.setEmail(user.getEmail());
        u.setTel_num(user.getTelNum());
        u.setWechat_abt(user.getWechatAbt());
        u.setAvatar_url(user.getAvatarUrl());
        u.setRole_num(user.getRoleNum());
        u.setFreeze_ornnt(user.getFreezeOrnnt());
        u.setAccount_money(user.getAccountMoney());
        u.setB_account(user.getbAccount());
        u.setUpdate_tm(new Timestamp(System.currentTimeMillis()));


        ResponseDTO res = new ResponseDTO(); // 结果返回封装

        int rows = userInfoMapper.updateById(u);
        if (rows > 0){
            res.setCode(200);
            res.setData(rows);
            res.setMsg("修改成功");
        } else {
            res.setCode(200);
            res.setData(0);
            res.setMsg("修改失败");
        }
        return res;
    }

    /** ====================== 后台用户管理接口 ============================ */


}
